package com.sxpi.course.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.sxpi.course.dto.CourseDto;
import com.sxpi.course.feign.api.CourseServiceFeign;
import com.sxpi.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @Author: 董伟豪
 * @Date: 2022/10/13 17:04
 */
@RestController
@Slf4j
public class CourseController extends BaseController {

    @Autowired
    private CourseServiceFeign courseServiceFeign;

    // 新建一个线程对象
    ExecutorService executorService = Executors.newCachedThreadPool();

/*
    ExecutorService threadPool = new ThreadPoolExecutor(
            2,
            5,
            3,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(3),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.DiscardOldestPolicy());
*/

    /**
     * 合并请求
     * @return
     * @throws InterruptedException
     */
    @PostMapping("/index")
    public R findCoursePage() throws InterruptedException {

        JSONObject jsonObject = new JSONObject();
        // 闭锁 （栅栏）
        CountDownLatch countDownLatch = new CountDownLatch(2);
        // 线程1
        executorService.submit(() -> {//100ms
            //课程分页查询
            jsonObject.put("coursePage",courseServiceFeign.findCoursePage(new CourseDto()));
            countDownLatch.countDown();
        });

        // 线程2
        executorService.submit(() -> {//200ms
            //2 : 统计浏览器
            jsonObject.put("categories",courseServiceFeign.findCategories());
            countDownLatch.countDown();
        });
        // 拦截--- 这里是一堵墙壁 ，这里一定是转化成0才会放开
        countDownLatch.await();
        return R.ok(jsonObject);
    }

    /**
     * 查询课程信息并分页和搜索
     * @param courseDto
     * @return
     */
    @PostMapping("/page")
    public R findCoursePage(@RequestBody CourseDto courseDto){
        return courseServiceFeign.findCoursePage(courseDto);
    }

    /**
     * 查询全部分类
     * @return
     */
    @PostMapping("/category")
    public R findCategories(){
        return courseServiceFeign.findCategories();
    }

    /**
     * 根据id查询出来的分类信息放入到缓存中
     * @param id
     * @return
     */
    @PostMapping("/get/{id}")
    public R getCourseDetail(@PathVariable("id")Long id){
        // 查询用户点赞总数
        R r = courseServiceFeign.countByCourseId(id);
        Integer count = MapUtil.getInt(r, "count");
        // 查询用户是否点赞该课程（如果用户没有登录）
        Object userIdObj = null;
        try{
            // 因为getSession直接抛出410，让前端直接进入登录页面我这里改写sa-token自带的异常
            userIdObj = StpUtil.getSession().get("userId");
        }catch (Exception ex){
            // 用户没有登录
            return courseServiceFeign.getCourseDetail(id)
                    .put("pariseCount",count);
        }
        long userId = Long.parseLong(String.valueOf(userIdObj));
        R r1 = courseServiceFeign.selectByCourseIdAndUserId(id, userId);
        String coursePrise = MapUtil.getStr(r1, "coursePrise");
        // 判断用户是否点过赞
        Boolean flag = coursePrise != null;
        // 用户登录
        return courseServiceFeign.getCourseDetail(id)
                .put("pariseCount",count)
                .put("userParise",flag);
    }

    /**
     * 查询相关课程信息
     * @return
     */
    @PostMapping("/relation")
    public R findCoursePageRelation(@RequestBody CourseDto courseDto){
        return courseServiceFeign.findCoursePageRelation(courseDto);
    }

    /**
     * 根据课程id查询对应章节的信息
     * @param courseId 课程id
     * @return
     */
    @PostMapping("/chapterlesson/{courseId}")
    public R getChapterLessonDetail(@PathVariable("courseId")Long courseId){
        return courseServiceFeign.getChapterLessonDetail(courseId);
    }

    /**
     * 根据课程id查询对应章节的信息（去除空字段）
     * @param courseId
     * @return
     */
    @PostMapping("/chapterlessonmap/{courseId}")
    public R getChapterLessonDetailMap(@PathVariable("courseId")Long courseId) {
        return courseServiceFeign.getChapterLessonDetailMap(courseId);
    }

    /**
     * 测试sentinel
     * @return
     */
    @PostMapping("/sentinel/test")
    public R findSentinelByZeroTest(){
        return courseServiceFeign.findSentinelByZeroTest();
    }


}
